var DeptTransfer = function () {
  var template = /*html*/ `
    <div class="dept-transfer">
      <div class="dept-transfer-panel">
        <div class="dept-transfer-title">选择</div>
        <div class="dept-transfer-transfer">
          <div class="filter-input">
            <el-input size="small" v-model="queryData" style="width:100%;" placeholder="过滤条件" @input="filterData"></el-input>
          </div>
          <div class="tree-path">
            <el-breadcrumb separator=">">
              <el-breadcrumb-item v-for="(data,index) in treePath" :key="'path_'+index">
                <span class="tree-path-item" :class="{select:pathIndex===index}" @click="toTreepath(data,index)">{{data.name}}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="dept-transfer-tree">
            <div>
              <el-checkbox :value="getCheckAll()" @change="allCheckedChange" :disabled="!canCheckAll()">全选</el-checkbox>
            </div>
            <div v-for="(data,index) in currentTree" :key="'tree_'+index">
              <el-checkbox v-if="data.checked!==undefined" v-model="data.checked">{{data.name}}</el-checkbox>
              <span v-else>{{data.name}}</span>
              <div class="subLevel" :class="{disabled:data.checked}" v-if="data.children!==undefined" @click="toSubLevel(data)">下级</div>
            </div>
          </div>
        </div>
      </div>
      <div style="width:15px;"></div>
      <div class="dept-transfer-panel">
        <div class="dept-transfer-title">已选</div>
        <div class="dept-transfer-transfer">
          <div class="dept-transfer-tree">
            <div v-for="(data,index) in getSelectTreeData()" :key="'selectTree_'+index">
              <span>{{data.name}}</span>
              <i class="dept-person-remove el-icon-circle-close" @click="removeSelect(data)"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  `;

  return {
    props: {
      value: {
        required: true
      },
      persons: {
        type: Array,
        default: function () {
          return [];
        }
      },
      mode: {
        type: String,
        default: ''
      }
    },

    data: function () {
      var treeData = this.getTreeData(this.persons);
      var treePersons = [];
      this.setTreePersons(treeData, treePersons);
      var list = ['dept', 'user'];
      treePersons = _.orderBy(treePersons, [function (obj) {
        return list.indexOf(obj.preStr);
      }]);
      return {
        treePersons: treePersons,
        currentTree: treeData,
        checkedAll: false,
        treePath: [{
          name: '通讯录',
          data: treeData
        }],
        pathIndex: 0,
        queryData: '',
        treeMode: 'tree'
      };
    },
    mounted: function () {
      var data = this.value;
      this.setData(data);
    },
    methods: {
      getTreeData: function (persons) {
        var attrs = [{
          id: 'deptId',
          name: 'deptName',
          preStr: 'dept'
        }, {
          id: 'userId',
          name: 'userName',
          preStr: 'user'
        }];

        persons = _.cloneDeep(persons);
        var personGroup = this.getGroupData(persons, attrs);
        var treeData = [];
        this.format2Tree(personGroup, treeData);
        return treeData;
      },

      getGroupData: function (persons, attrs) {
        var len = persons.length;
        var mode = this.mode;
        var personGroup = {};
        for (var i = 0; i < len; i++) {
          var person = persons[i];
          for (var j = 0; j < attrs.length; j++) {
            var attr = attrs[j];
            var value = person[attr.id];
            if (value === undefined) {
              continue;
            }

            var node = {
              id: `${attr.preStr}_${person[attr.id]}`,
              name: person[attr.name],
              preStr: attr.preStr
            };
            if (mode !== 'leader'){
              node.checked = false;
            } else {
              if (attr.preStr === 'user'){
                node.checked = false;
              }
            }
            if (j === attrs.length - 1) {
              node.person = person;
            }

            var path = this.getGroupPath(person, attrs.slice(0, j + 1));
            if (_.get(personGroup, path) === undefined) {
              _.set(personGroup, `${path}.data`, node);
            }
          }
        }
        return personGroup;
      },

      getGroupPath: function (person, attrs) {
        var pathList = [];
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          var id = attr.id;
          var value = person[id];
          if (value === undefined || value === null || value === '') {
            continue;
          }
          pathList.push(`${attr.preStr}_${value}`);
        }
        return pathList.join('.');
      },

      format2Tree: function (personGroup, treeData) {
        for (var key in personGroup) {
          if (key === 'data') {
            continue;
          }
          var obj = personGroup[key];
          var data = obj.data;
          if (data === undefined) {
            return;
          }

          treeData.push(data);
          if (SysUtil.getObjectFieldCount(obj) > 1) {
            data.children = [];
            this.format2Tree(obj, data.children);
          }
        }
      },

      setTreePersons: function (treeData, treePersons) {
        for (var i = 0; i < treeData.length; i++) {
          var data = treeData[i];
          treePersons.push(data);
          var children = data.children;
          if (children === undefined) {
            continue;
          }
          this.setTreePersons(children, treePersons);
        }
      },

      toSubLevel: function (data) {
        if (data.checked) {
          return;
        }
        this.currentTree = data.children;
        this.treePath.push({
          name: data.name,
          data: data.children
        });
        this.pathIndex++;
      },

      toTreepath: function (path, index) {
        if (this.pathIndex === index) {
          if (this.treeMode === 'search') {
            this.currentTree = path.data;
            this.treeMode = 'tree';
          }
          return;
        }
        var treePath = this.treePath;
        treePath.splice(index + 1);
        this.currentTree = path.data;
        this.pathIndex = index;
        this.treeMode = 'tree';
      },

      getCheckAll: function () {
        var currentTree = this.currentTree;
        var obj = _.find(currentTree, function(person){
          var checked = person.checked;
          return !checked;
        });
        return obj === undefined;
      },

      canCheckAll:function(){
        var currentTree = this.currentTree;
        var obj =  _.find(currentTree,function(data){
          return data.checked !== undefined;
        });
        return obj !== undefined;
      },

      allCheckedChange: function (checked) {
        var currentTree = this.currentTree;
        currentTree = _.filter(currentTree, function(obj){
          return obj.checked !== undefined;
        });
        var len = currentTree.length;
        for (var i = 0; i < len; i++) {
          var data = currentTree[i];
          data.checked = checked;
        }
      },

      filterData: function () {
        var queryData = this.queryData;
        var treePath = this.treePath;
        var treePersons = this.treePersons;
        var currentTree;
        if (queryData !== '') {
          queryData = _.toLower(queryData);
          currentTree = _.filter(treePersons, function (obj) {
            var name = obj.name;
            name = _.toLower(name);
            return name.indexOf(queryData) !== -1;
          });
          this.treeMode = 'search';
        } else {
          currentTree = treePath[treePath.length - 1].data;
          this.treeMode = 'tree';
        }
        this.currentTree = currentTree;
      },

      getSelectTreeData: function () {
        var treePersons = this.treePersons;
        treePersons = _.filter(treePersons, {
          checked: true
        });
        return treePersons;
      },

      removeSelect:function(treePerson){
        treePerson.checked = false;
      },

      getData: function () {
        var mode = this.mode;
        if (mode === 'leader') {
          return this.getLeaderData();
        } else if (mode === 'attendance') {
          return this.getAttendanceData();
        }
        return null;
      },

      getLeaderData: function () {
        var leaders = [];
        var treePersons = this.treePersons;
        treePersons = _.filter(treePersons, {
          checked: true
        });
        var len = treePersons.length;
        for (var i = 0; i < len; i++) {
          var person = treePersons[i];
          var id = person.id;
          var personId = id.split('_')[1];
          personId = Number(personId);
          var obj = {
            id: personId,
            name: person.name
          };
          leaders.push(obj);
        }
        return leaders;
      },

      getAttendanceData: function () {
        var depts = [];
        var persons = [];
        var treePersons = this.treePersons;
        treePersons = _.filter(treePersons, {
          checked: true
        });

        var len = treePersons.length;
        for (var i = 0; i < len; i++) {
          var person = treePersons[i];
          var id = person.id;
          var personId = id.split('_')[1];
          personId = Number(personId);
          var obj = {
            id: personId,
            name: person.name
          };
          if (id.startsWith('user_')) {
            persons.push(obj);
          } else if (id.startsWith('dept_')) {
            depts.push(obj);
          }
        }
        return {
          depts: depts,
          persons: persons
        };
      },

      setData: function (data) {
        var mode = this.mode;
        if (mode === 'leader') {
          this.pushData(data, 'user');
        } else if (mode === 'attendance') {
          this.pushData(data.depts, 'dept');
          this.pushData(data.persons, 'user');
        }
      },

      pushData(array, preStr) {
        var treePersons = this.treePersons;
        var len = treePersons.length;
        for (var i = 0; i < len; i++) {
          var person = treePersons[i];
          var id = person.id;
          var strs = id.split('_');
          if (strs[0] !== preStr) {
            continue;
          }
          var personId = Number(strs[1]);
          if (array.indexOf(personId) !== -1) {
            person.checked = true;
          }
        }
      }
    },
    template: template
  };
}();